import equipmentService, { type PageListReq } from "@/api/services/eam/equipmentService";
import CustomTable from "@/components/grid/CustomTable";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { Button, Card, Col, DatePicker, Drawer, Form, Input, Row, Select, Space, Spin, Switch } from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { EamEquipment } from "./entity";

import equipmentTypeService from "@/api/services/eam/equipmentTypeService";
import workshopService from "@/api/services/mes/workshopService";
import type { MesWorkshop } from "@/pages/mes/workshop/entity";
import { LoadingOutlined, PlusOutlined, UserAddOutlined } from "@ant-design/icons";
import Upload, { type RcFile, type UploadChangeParam, type UploadFile, type UploadProps } from "antd/es/upload";
import type { EamEquipmentType } from "../equipmentType/entity";
import "./index.css";
import type { SysAttachment } from "@/pages/system/attachment/entity";
import SingleUserSelector from "@/pages/components/selector/SingleUserSelect";
import { UserInfo } from "#/entity";

const { TextArea } = Input;

export default function EamEquipmentPage() {
	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		code: undefined,
		type: undefined,
		workshopId: undefined,
		resourceCode: undefined,
		machineCode: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<EamEquipment[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<EamEquipment | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	const [workshopOptions, setWorkshopOptions] = useState<MesWorkshop[]>([]);
	const [typeOptions, setTypeOptions] = useState<EamEquipmentType[]>([]);

	const [uploadLoading, setUploadLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>();

	const [userSelectVisiable, setUserSelectVisiable] = useState(false);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	useEffect(() => {
		getWorkshopOptions();
		getTypeOptions();
	}, []);

	const useStateOptions = useDictionary("equipment_use_status");

	const columns: ColumnsType<EamEquipment> = [
		{
			title: "设备编码",
			width: 120,
			key: "code",
			dataIndex: "code",
		},
		{
			title: "设备名称",
			width: 120,
			key: "name",
			dataIndex: "name",
		},
		{
			title: "设备类型",
			width: 120,
			key: "typeName",
			dataIndex: "typeName",
		},
		{
			title: "设备型号",
			width: 120,
			key: "model",
			dataIndex: "model",
		},
		{
			title: "车间",
			width: 120,
			key: "workshopName",
			dataIndex: "workshopName",
		},
		{
			title: "资产编码",
			width: 120,
			key: "resourceCode",
			dataIndex: "resourceCode",
		},
		{
			title: "设备负责人",
			width: 120,
			key: "resourceOwnerName",
			dataIndex: "resourceOwnerName",
		},
		{
			title: "入库日期",
			width: 120,
			key: "stockInDate",
			dataIndex: "stockInDate",
		},
		{
			title: "使用状态",
			width: 120,
			key: "useStatus",
			align: "center",
			dataIndex: "useStatus",
			render: (_, record) => <TableDictTag dictCode="equipment_use_status" value={record.useStatus ?? ""} />,
		},
		{
			title: "供应商",
			width: 120,
			key: "supplier",
			dataIndex: "supplier",
		},
		{
			title: "机身编号",
			width: 120,
			key: "machineCode",
			dataIndex: "machineCode",
		},
		{
			title: "使用年限（年）",
			width: 120,
			align: "center",
			key: "durableYears",
			dataIndex: "durableYears",
		},
		{
			title: "保修截止日期",
			width: 120,
			key: "warrantyExpirationDate",
			dataIndex: "warrantyExpirationDate",
		},
		{
			title: "虚拟设备",
			width: 120,
			align: "center",
			key: "virtualDevice",
			dataIndex: "virtualDevice",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.virtualDevice ?? ""} />,
		},
		{
			title: "重点设备",
			width: 120,
			align: "center",
			key: "keyEquipment",
			dataIndex: "keyEquipment",
			render: (_, record) => <TableDictTag dictCode="system_true_false" value={record.keyEquipment ?? ""} />,
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		equipmentService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (eamEquipment: EamEquipment) => {
		setEditingData(eamEquipment);
		form.setFieldsValue(eamEquipment);
		if (eamEquipment.image) {
			const baseUrl = import.meta.env.VITE_API_URL;
			setImageUrl(`${baseUrl}/system/attachment/download/${eamEquipment.image}`);
		}

		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (eamEquipment: EamEquipment) => {
		setEditingData(eamEquipment);
		form.setFieldsValue(eamEquipment);
		if (eamEquipment.image) {
			const baseUrl = import.meta.env.VITE_API_URL;
			setImageUrl(`${baseUrl}/system/attachment/download/${eamEquipment.image}`);
		}
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: EamEquipment) => {
		try {
			setSubmitLoading(true);

			const data = {
				...values,
				id: editingData?.id,
				virtualDevice: values.virtualDevice ? 1 : 0,
				keyEquipment: values.keyEquipment ? 1 : 0,
			};
			if (editingData) {
				await equipmentService.update(data);
				toast.success("更新设备台账成功");
			} else {
				await equipmentService.add(data);
				toast.success("创建设备台账成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setImageUrl(undefined);
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await equipmentService.remove(selectedRowKeys);
			toast.success("删除设备台账成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	// 获取车间下拉列表
	const getWorkshopOptions = () => {
		workshopService
			.getWorkshopSelectList()
			.then((res) => {
				setWorkshopOptions(res);
			})
			.catch((error) => {
				console.error("获取车间列表失败：", error);
				toast.error("获取车间列表失败");
			});
	};

	// 获取类型下拉列表
	const getTypeOptions = () => {
		equipmentTypeService
			.getTypeSelectList()
			.then((res) => {
				setTypeOptions(res);
			})
			.catch((error) => {
				console.error("获取设备类型列表失败：", error);
				toast.error("获取设备类型列表失败");
			});
	};

	const getBase64 = (img: RcFile, callback: (url: string) => void) => {
		const reader = new FileReader();
		reader.addEventListener("load", () => callback(reader.result as string));
		reader.readAsDataURL(img);
	};

	const beforeUpload = (file: RcFile) => {
		const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
		if (!isJpgOrPng) {
			toast.error("You can only upload JPG/PNG file!");
		}
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isLt2M) {
			toast.error("Image must smaller than 2MB!");
		}
		return isJpgOrPng && isLt2M;
	};

	const handleChange: UploadProps["onChange"] = (info: UploadChangeParam<UploadFile>) => {
		if (info.file.status === "uploading") {
			setUploadLoading(true);
			return;
		}
		if (info.file.status === "done") {
			// Get this url from response in real world.
			getBase64(info.file.originFileObj as RcFile, (url) => {
				setUploadLoading(false);
				setImageUrl(url);
			});

			const attachment: SysAttachment = info.file.response?.data;
			form.setFieldsValue({
				image: attachment.id,
			});
		}
	};

	const uploadButton = (
		<div>
			{uploadLoading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>上传图片</div>
		</div>
	);

	 const showUserSelect = () => {
			setUserSelectVisiable(true);
		};
		const handleSelectUser = (user?: UserInfo) => {
			form.setFieldsValue({
				resourceOwner: user?.id,
				resourceOwnerName: user?.name,
			});
			setUserSelectVisiable(false);
		};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="code" label="设备编码">
						<Input allowClear placeholder="请输入设备编码" />
					</Form.Item>

					<Form.Item name="type" label="设备类型">
						<Select
							placeholder="请选择设备类型"
							style={{ width: 160 }}
							options={typeOptions.map((item) => ({
								label: item.name,
								value: item.id,
							}))}
							allowClear
						/>
					</Form.Item>

					<Form.Item name="workshopId" label="车间">
						<Select
							placeholder="请选择车间"
							style={{ width: 160 }}
							options={workshopOptions.map((item) => ({
								label: item.name,
								value: item.id,
							}))}
							allowClear
						/>
					</Form.Item>

					<Form.Item name="resourceCode" label="资产编码">
						<Input allowClear placeholder="请输入资产编码" />
					</Form.Item>

					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑设备台账" : "新增设备台账"}
				width={1000}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Row gutter={24}>
						<Col span={8}>
							<Row>
								<Col span={24}>
									<Form.Item
										name="code"
										label="设备编码"
										rules={[
											{
												required: true,
												message: "请填写设备编码",
											},
										]}
									>
										<Input placeholder="请输入设备编码" allowClear />
									</Form.Item>
								</Col>
							</Row>
							<Row>
								<Col span={24}>
									<Form.Item
										name="type"
										label="设备类型"
										rules={[
											{
												required: true,
												message: "请填写设备类型",
											},
										]}
									>
										<Select
											placeholder="请选择设备类型"
											options={typeOptions.map((item) => ({
												label: item.name,
												value: item.id,
											}))}
											allowClear
										/>
									</Form.Item>
								</Col>
							</Row>
							<Row>
								<Col span={24}>
									<Form.Item name="model" label="设备型号">
										<Input placeholder="请输入设备型号" allowClear />
									</Form.Item>
								</Col>
							</Row>
						</Col>
						<Col span={8}>
							<Row>
								<Col span={24}>
									<Form.Item
										name="name"
										label="设备名称"
										rules={[
											{
												required: true,
												message: "请填写设备名称",
											},
										]}
									>
										<Input placeholder="请输入设备名称" allowClear />
									</Form.Item>
								</Col>
							</Row>
							<Row>
								<Col span={24}>
									<Form.Item name="workshopId" label="车间">
										<Select
											placeholder="请选择车间"
											options={workshopOptions.map((item) => ({
												label: item.name,
												value: item.id,
											}))}
											allowClear
										/>
									</Form.Item>
								</Col>
							</Row>
							<Row>
								<Col span={24}>
									<Form.Item name="resourceCode" label="资产编码">
										<Input placeholder="请输入资产编码" allowClear />
									</Form.Item>
								</Col>
							</Row>
						</Col>
						<Col span={8} style={{ display: "flex" }}>
							<Form.Item
								name="file"
								label="设备图片"
								style={{
									flex: 1,
									display: "flex",
									flexDirection: "column",
								}}
							>
								<Upload
									listType="picture-card"
									accept=".jpg, .jpeg, .png, .gif, .bmp, .webp"
									showUploadList={false}
									action="/api/system/attachment/upload"
									beforeUpload={beforeUpload}
									onChange={handleChange}
								>
									{imageUrl ? (
										<img src={imageUrl} alt="avatar" style={{ width: "138px", height: "138px" }} />
									) : (
										uploadButton
									)}
								</Upload>

								<Form.Item name="image" label="图片" hidden>
									<Input />
								</Form.Item>
							</Form.Item>
						</Col>
					</Row>

					<Row gutter={24}>
						<Col span={8}>
						<Form.Item name="resourceOwner" label="设备负责人" hidden>
                <Input />
              </Form.Item>
							<Form.Item name="resourceOwnerName" label="设备负责人">
								<Input.Search
                  placeholder="请选择设备负责人"
                  allowClear
                  enterButton={<UserAddOutlined />}
                  onSearch={showUserSelect}
                />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								name="stockInDate"
								label="入库日期"
								getValueFromEvent={(value) => {
									return value ? value.format("YYYY-MM-DD") : null;
								}}
								getValueProps={(value) => ({
									value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
								})}
							>
								<DatePicker
									style={{ width: "100%" }}
									format="YYYY-MM-DD"
									onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
								/>
							</Form.Item>
						</Col>

						<Col span={8}>
							<Form.Item name="machineCode" label="机身编号">
								<Input placeholder="请输入机身编号" allowClear />
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={8}>
							<Form.Item name="supplier" label="供应商">
								<Input placeholder="请输入供应商" allowClear />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item name="durableYears" label="使用年限（年）">
								<Input placeholder="请输入使用年限（年）" allowClear />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								name="warrantyExpirationDate"
								label="保修截止日期"
								getValueFromEvent={(value) => {
									return value ? value.format("YYYY-MM-DD") : null;
								}}
								getValueProps={(value) => ({
									value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
								})}
							>
								<DatePicker
									style={{ width: "100%" }}
									format="YYYY-MM-DD"
									onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={8}>
							<Form.Item
								name="virtualDevice"
								label="虚拟设备"
								valuePropName="checked"
								normalize={(value) => value === 1}
								getValueFromEvent={(checked) => (checked ? 1 : 0)}
							>
								<Switch checkedChildren="是" unCheckedChildren="否" disabled={isView} />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item
								name="keyEquipment"
								label="重点设备"
								valuePropName="checked"
								normalize={(value) => value === 1}
								getValueFromEvent={(checked) => (checked ? 1 : 0)}
							>
								<Switch checkedChildren="是" unCheckedChildren="否" disabled={isView} />
							</Form.Item>
						</Col>
						<Col span={8}>
							<Form.Item name="useStatus" label="使用状态">
								<Select placeholder="请选择设备类型" allowClear options={useStateOptions} />
							</Form.Item>
						</Col>
					</Row>
					<Row gutter={24}>
						<Col span={24}>
							<Form.Item name="remark" label="备注" labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
								<TextArea />
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</Drawer>

			      {/* 用户选择器 */}
      <SingleUserSelector
        open={userSelectVisiable}
        onCancel={() => setUserSelectVisiable(false)}
        onOk={(selectUser) => handleSelectUser(selectUser)}
      />
		</Spin>
	);
}
